package com.zlkj.pro.modular.wechat.controller;

import cn.stylefeng.roses.kernel.rule.pojo.response.ResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.SuccessResponseData;
import cn.stylefeng.roses.kernel.rule.util.HttpServletUtil;
import cn.stylefeng.roses.kernel.scanner.api.annotation.ApiResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.GetResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.PostResource;
import com.alibaba.fastjson.JSON;
import com.zlkj.pro.core.consts.ProjectConstants;
import com.zlkj.pro.core.expander.WxConfigExpander;
import com.zlkj.pro.core.util.SignUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMenuService;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.freepublish.WxMpFreePublishList;
import me.chanjar.weixin.mp.bean.menu.WxMpGetSelfMenuInfoResult;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@RestController
@ApiResource(name = "验证公众号", path = ProjectConstants.SERVICE_APP_PREFIX)
public class WeChatController {

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WxMpMessageRouter messageRouter;

    /**
     * 获取列表
     *
     * @author lb
     * @date 2021/12/10 15:00
     */
    @GetResource(code = "$get", name = "验证公众号", path = "/wechat/checkSign", requiredLogin = false, requiredPermission = false)
    public String get(String signature, String timestamp, String nonce, String echostr) {
        try {
            if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                return echostr;
            }
        } catch (Exception e) {
            log.error("验证公众号token失败", e);
        }
        return null;
    }


    /**
     * 微信获取消息
     */
    @PostResource(code = "$post", name = "微信获取消息", path = "/wechat/checkSign", requiredLogin = false, requiredPermission = false)
    public void post(@RequestBody String requestBody,
                     @RequestParam("signature") String signature,
                     @RequestParam("timestamp") String timestamp,
                     @RequestParam("nonce") String nonce,
                     @RequestParam("openid") String openid,
                     @RequestParam(name = "encrypt_type", required = false) String encType,
                     @RequestParam(name = "msg_signature", required = false) String msgSignature,
                     HttpServletRequest request,
                     HttpServletResponse response) throws IOException {

        log.info("微信获取消息！");

        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }

        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return;
            }
            out = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxMpService.getWxMpConfigStorage(),
                    timestamp, nonce, msgSignature);
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return;
            }

            out = outMessage.toEncryptedXml(wxMpService.getWxMpConfigStorage());
        }

        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.print(out);
        writer.close();
    }

    private WxMpXmlOutMessage route(WxMpXmlMessage message) {
        try {
            return this.messageRouter.route(message);
        } catch (Exception e) {
            log.error("路由消息时出现异常！", e);
        }

        return null;
    }

    @GetResource(name = "测试发送模板消息", path = "/wechat/sendTemplateMsg", requiredLogin = false, requiredPermission = false)
    public void sendTemplateMsg(String openId, String appId, String path) {

        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openId)
                .templateId("n6HcfuWewTd2gOEFiBt1iLBSLK4m36lWoHodJtD-NQw")
                .miniProgram(new WxMpTemplateMessage.MiniProgram(appId, path, Boolean.FALSE))
                .build();

        templateMessage.addData(new WxMpTemplateData("character_string2", "20220429033105D3T5R", "#000000"));
        templateMessage.addData(new WxMpTemplateData("thing4", "张三", "#000000"));
        templateMessage.addData(new WxMpTemplateData("thing6", "李四(LL大连代理商)", "#000000"));
        templateMessage.addData(new WxMpTemplateData("thing8", "申请成功，BMSH审批中", "#000000"));
        templateMessage.addData(new WxMpTemplateData("time9", "2024.05.16 19:00", "#000000"));
        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("测试发送模板消息时出现异常！{}", e.getMessage());
        }
    }

    @GetResource(name = "获取素材ID", path = "/wechat/getArticleId", requiredLogin = false, requiredPermission = false)
    public ResponseData getArticleId(int offset, int count) {
        try {
            WxMpFreePublishList publicationRecords = wxMpService.getFreePublishService().getPublicationRecords(offset, count, 1);
            return new SuccessResponseData(publicationRecords);
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("获取素材ID时出现异常！{}", e.getMessage());
        }
        return null;
    }
    @GetResource(name = "获取自定义菜单配置接口", path ="/getSelfMenuInfo", requiredLogin = false, requiredPermission = false)
    public ResponseData getSelfMenuInfo() throws WxErrorException {
        return new SuccessResponseData(wxMpService.getMenuService().getSelfMenuInfo());
    }

    @GetResource(name = "新增公众号菜单", path = "/wechat/menu/add", requiredLogin = false, requiredPermission = false)
    public void addMenu() {
        WxMpMenuService menuService = wxMpService.getMenuService();
        String contextPath = HttpServletUtil.getRequest().getContextPath();
        log.info("微信获取消息！miniprogram");
        WxMenu wxMenu = new WxMenu();
        WxMenuButton wxMenuButton = new WxMenuButton();
        wxMenuButton.setName("技术支持");
        List<WxMenuButton> subButtons1 = new ArrayList<>();

        WxMenuButton subButton1 = new WxMenuButton();
        subButton1.setType("article_id");
        subButton1.setName("GT小讲堂");
        subButton1.setArticleId("");
        subButtons1.add(subButton1);

        WxMenuButton subButton2 = new WxMenuButton();
        subButton2.setType("article_id");
        subButton2.setName("长期休假前保养");
        subButton2.setArticleId("");
        subButtons1.add(subButton2);

        wxMenuButton.setSubButtons(subButtons1);


        WxMenuButton wxMenuButton2 = new WxMenuButton();
        wxMenuButton2.setName("产品介绍");
        List<WxMenuButton> subButtons = new ArrayList<>();
        WxMenuButton button1 = new WxMenuButton();
        button1.setType("view");
        button1.setName("GTXPRO产品彩页");
        button1.setUrl("https://www.brother.cn/garmentprinter/-/media/machinery/product/garment/doc/GTXPRO-catalog.ashx");
        subButtons.add(button1);

        WxMenuButton button2 = new WxMenuButton();
        button2.setType("view");
        button2.setName("GTXPRO B产品彩页");
        button2.setUrl("https://www.brother.cn/garmentprinter/-/media/machinery/product/garment/doc/GTXPROB-catalog.ashx");
        subButtons.add(button2);

        WxMenuButton button3 = new WxMenuButton();
        button3.setType("article_id");
        button3.setName("GTXPRO产品视频");
        button3.setArticleId("");
        subButtons.add(button3);

        WxMenuButton button4 = new WxMenuButton();
        button4.setType("article_id");
        button4.setName("大规模生产");
        button4.setArticleId("");
        subButtons.add(button4);
        wxMenuButton2.setSubButtons(subButtons);


        WxMenuButton wxMenuButton3 = new WxMenuButton();
        wxMenuButton3.setType("click");
        wxMenuButton3.setName("联系我们");
        wxMenuButton3.setKey("contact");

        wxMenu.setButtons(Arrays.asList(wxMenuButton, wxMenuButton2, wxMenuButton3));
        log.info("微信获取消息 /pagesB/instituIn/index?identifies=PLATFORM_INTRODUCTION {}", JSON.toJSON(wxMenu));
        try {
            menuService.menuDelete();
            menuService.menuCreate(wxMenu);
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("新增公众号菜单时出现异常！{}", e.getMessage());
        }
    }

}
